import { SignalWatcher, computed, signal, withWatch } from "@lit-labs/signals";
import * as d3 from "d3";
import { LitElement, css, html, svg as coreSvg } from "lit";
import { repeat } from "lit/directives/repeat.js";

// import type { Numeric } from "d3";

const width = 640;
const height = 400;

const marginTop = 20;
const marginRight = 20;
const marginBottom = 20;
const marginLeft = 20;

const data = signal(d3.ticks(-2, 2, 200).map((d) => Math.sin(d)));

const svg = withWatch(coreSvg);
/**
 * @param {number} i
 * @returns {number}
 */
const x = (i) =>
  d3.scaleLinear(
    [0, data.get().length - 1],
    [marginLeft, width - marginRight],
  )(i);
/**
 * @param {number} i
 * @returns {number}
 */
const y = (i) =>
  // @ts-expect-error
  // eslint-disable-next-line jsdoc/no-bad-blocks
  d3.scaleLinear(/* @type {number, number, never} */ d3.extent(data.get()), [
    height - marginBottom,
    marginTop,
  ])(i);
/**
 * @returns {string | null}
 */
function line() {
  return d3.line((d, i) => x(i), y)(data.get());
}

export class D3Lit extends SignalWatcher(LitElement) {
  /**
   * @override
   */
  static styles = css`
    @namespace svg url(http://www.w3.org/2000/svg);
    :host {
      --display: block;
      --width: 100%;
      --height: 100%;
    }
  `;

  constructor() {
    super();
    // document.createElementNS("http://www.w3.org/2000/svg", "svg");
  }

  /**
   * @param {MouseEvent} event
   */
  onMousemove(event) {
    const [x, y] = d3.pointer(event, this.shadowRoot);
    // console.log(x, y);
    data.set([...data.get().slice(-200), Math.atan2(x, y)]);
  }

  // onResize() {
  //   if (this.resizeObserver) {
  //     return;
  //   }
  //   this.resizeObserver = new ResizeObserver((entries) => {
  //     for (const entry of entries) {
  //       if (entry.contentBoxSize) {
  //         // Checking for chrome as using a non-standard array
  //         if (entry.contentBoxSize[0]) {
  //           const elemSize = entry.contentBoxSize[0];
  //           // elemSize.blockSize: height
  //           console.log("contentBoxSize", elemSize.inlineSize); // width
  //         }
  //       } else if (entry.borderBoxSize) {
  //         console.log(entry.contentRect);
  //         if (entry.borderBoxSize[0]) {
  //           const elemSize = entry.borderBoxSize[0];
  //           // elemSize.blockSize: height
  //           console.log("borderBoxSize", elemSize.inlineSize); // width
  //         }
  //       }
  //     }
  //   });
  //   this.resizeObserver.observe(this);
  // }
  handleClick() {
    console.log("D3Lit", this);
  }

  /**
   * @override
   * @returns {import('lit').TemplateResult<1>}
   */
  render() {
    return html`
      <svg
        width=${width}
        height=${height}
        @mousemove=${this.onMousemove}
        xmlns="http://www.w3.org/2000/svg"
      >
        <path fill="none" stroke="currentColor" strokeWidth="1.5" d=${line()} />
        <g stroke="currentColor" fill="white" strokeWidth="1.5">
          ${repeat(
            data.get(),
            (d, i) => `${d}-${i}`,
            (d, i) => svg`<circle cx=${x(i)} cy=${y(d)} r="2.5"/>`,
          )}
        </g>
      </svg>
    `;
  }
}

window.customElements.define("d3-lit", D3Lit);
